<?php

namespace app\back\controller;

use app\back\model\Role;
use priv\Privilege;
use \think\Controller;
use app\back\model\Admin;
use app\back\validate\AdminValidate;
use think\Db;
use think\Session;


class AdminController extends Controller
{


    //添加修改商品
    public function setAction()
    {
        $req = request();
        if ($req->isGet()) {
            $m = session("message");
            $i = session("info");
            $id = input("id");


            $one = Admin::get($id);
            if (!(isset($m) && isset($i))) {
                $message = "";
                $info = $one;
            } else {
                $message = $m;
                $info = $i;
            }
            $check_roles = [];
            if(!empty($id)){
                $check_roles = Db::name("admin_role")->where("admin_id",$id)->column("role_id");

            }
            $this->assign("msg", $message);
            $this->assign("info", $info);
            $this->assign("id", $id);
            $this->assign("role_list",Role::all());
            $this->assign("check_roles",$check_roles);
            return $this->fetch();
        } elseif ($req->isPost()) {
            $model = new Admin;
            $v = new  AdminValidate;
            $data = input("post.");
            $roles= input("roles/a",[]);
            if (!empty($data["id"])) {
                $v->scene("update");
            }
            if (!$v->batch(true)->check($data)) {
                $data["id"] = isset($data["id"]) ? $data["id"] : null;
                return $this->redirect("set", ["id" => $data["id"]], 202, [
                    "message" => $v->getError(),
                    "info" => $data
                ]);
            }
            $result = null;
            if (!empty($data["id"])) {
                $id = $data["id"];
                $one = $model->find($id);
                $result = $one->allowField(true)->save($data);
                $post_roles = $roles;
                $del_roles = Db::name("admin_role")->where("admin_id",$id)->column("role_id");
                $del_roles = array_diff($del_roles,$post_roles);
                //若所选与之前无差异，则不进行任何操作
                Db::name("admin_role")->where([
                    "admin_id" => $id,
                    "role_id" =>["in",$del_roles]
                ])->delete();
                $insert_roles = array_diff($post_roles,$del_roles);
                if(empty($del_roles)&&empty($insert_roles)){
                    return $this->redirect("index");

                }
                $insert_roles = array_map(function($param) use($id){
                    return [
                        "admin_id" => $id,
                        "role_id" => $param
                    ];
                },$insert_roles);
                Db::name("admin_role")->insertAll($insert_roles);
            } else {
                $result = $model->allowField(true)->save($data);
                //解析身份
                $id = $model->id;
                $roles_arr = $roles;
                $roles_arr = array_map(function ($param) use ($id){
                    return [
                        "admin_id"=> $id,
                        "role_id" => $param
                    ];
                },$roles_arr);
                //插入 用户_权限 表
                Db::name("admin_role")->insertAll($roles_arr);
            }
            if (!$result) {
                return "添加失败：" . $this->error();
            } else {
                return $this->redirect("index");
            }


        } else {


        }

    }


    //筛选(主页)
    public function indexAction()
    {

        $filter = input("filter/a");
        $filter_order = [];
        $m = new Admin();


        //筛选查询字段username

        if (isset($filter["username"])) {
            $str = str_replace("%", "\%", $filter["username"]);
            $m->where("username", "like", "%" . $str . "%");
            $filter_order["filter[username]"] = $filter["username"];
        }


        $order = input("order/a");
        if (isset($order)) {
            $m->order([$order["field"] => $order["type"]]);
        }
        $size = 5;
        $list = $m->paginate($size, false, ['query' => request()->param()]);
        $start = $size * ($list->currentPage() - 1) + 1;
//        $end =min($list->total(),$list->currentPage()*$size);
        $end = $start + count($list) - 1;
        $this->assign("start", $start);
        $this->assign("end", $end);
        $this->assign("list", $list);
        $this->assign("filter", $filter);
        $this->assign("order", $order);
        $this->assign("filter_order", $filter_order);
        return $this->fetch();
    }

    //修改密码
    public function repasswordAction()
    {
        $req = request();
        if ($req->isGet()) {
            $m = session("message");
            $i = session("info");
            $id = input("id");
            $one = Admin::get($id);
            if (!(isset($m) && isset($i))) {
                $message = "";
                $info = "";
            } else {
                $message = $m;
                $info = $i;
            }
            $this->assign("msg", $message);
            $this->assign("info", $info);
            $this->assign("id", $id);
            $this->assign("username", $one->username);
            return $this->fetch();
        } elseif ($req->isPost()) {
            $model = new Admin;
            $v = new  AdminValidate;
            $data = input("post.");
            if (!$v->scene("repassword")->batch(true)->check($data)) {
                return $this->redirect("repassword", ["id" => $data["id"]], 202, [
                    "message" => $v->getError(),
                    "info" => $data
                ]);
            }
            $result = null;
            if (!empty($data["id"])) {
                $one = $model->find($data["id"]);
                $result = $one->allowField(true)->save($data);
            } else {

            }
            if (!$result) {
                return "添加失败：" . $this->error();
            } else {
                return $this->redirect("index", ["id" => $data["id"]]);
            }


        } else {


        }


    }

    //删除

    public function multiAction()
    {
        $data = input("selected/a");
        if (count($data) == 0) $this->redirect("index");

        Admin::destroy($data);
        $this->redirect("index");
    }

    //登录界面
    public function loginAction()
    {

        if(session("admin")){
            return $this->redirect("site/index");
        }
        $req = request();
        if ($req->isGet()) {
            $this->assign("msg", session("msg"));
            return $this->fetch();

        } else {
            $username = input("username");
            $password = input("password");
            $data = compact("username", "password");
            $one = Admin::where($data)->find();

            if (!$one) {
                return redirect("admin/login", [], 302, [
                    "data" => input(),
                    "msg" =>"管理员信息不正确"
                ]);
            } else {


                session("admin", $one);
                $route =Session::has('route')?Session::pull('route'):'site/index';

                return $this->redirect($route);


            }

        }

    }
    //退出
    public function logoutAction()
    {
        session("admin",null);
//        Session::delete("admin");
        return redirect("admin/login");
    }


}





